package org.dromara.third.auth.web;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.BusinessServiceException;
import org.dromara.third.auth.beans.constans.ExceptionEnum;
import org.dromara.third.auth.service.AuthenticationService;
import org.dromara.third.auth.vo.TokenRequest;
import org.dromara.third.auth.vo.TokenResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 数据同步鉴权接口类
 *
 * @author admin
 * @date 2020/7/13 15:52
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/open/v1/")
public class AuthenticationController {

    private final AuthenticationService authenticationService;

    /**
     * 获取token
     *
     * @param request 参数封装类 {@link TokenRequest}
     * @return 返回Token类
     */
    @GetMapping("getToken")
    public R<TokenResponse> getToken(@ModelAttribute TokenRequest request) {
        //校验参数
        if (!checkParam(request)) {
            throw new BusinessServiceException(ExceptionEnum.AuthException01.getCode(), ExceptionEnum.AuthException01.getMessage());
        }
        log.info("{}请求获取token", request.getAppId());
        return R.ok(authenticationService.getToken(request));
    }

    /**
     * 验证token类
     *
     * @param token token值
     * @return token是否正确
     */
    @GetMapping("checkToken")
    public R<String> checkToken(String token) {
        //校验参数
        if (StringUtils.isEmpty(token)) {
            R.fail(ExceptionEnum.AuthException05.getMessage());
        }
        return authenticationService.checkToken(token);
    }


    /**
     * 参数检验
     *
     * @param request 请求入参
     * @return 是否通过校验
     */
    private boolean checkParam(TokenRequest request) {
        //验证参数request为空
        boolean check = true;
        if (null == request) {
            check = false;
        }
        //验证属性
        if (StringUtils.isEmpty(request.getAppId()) || StringUtils.isEmpty(request.getDigest()) ||
                StringUtils.isEmpty(request.getGrantType()) || StringUtils.isEmpty(request.getTimestamp())) {
            check = false;
        }
        return check;
    }

}
